<template>
    <div>
      <label for="city-input">请输入城市ID:</label>
      <input id="city-input" v-model="cityId" type="text">
      <button @click="searchWeatherForecast">搜索天气</button>
    <ul v-if="forecastData.length">
        <li v-for="(forecast, index) in forecastData" :key="index">
          {{ forecast.date }}: {{ forecast.textDay }} - {{ forecast.textNight }} - {{ forecast.tempMax }}°C/{{ forecast.tempMin }}°C  : {{ forecast.windDirDay }}{{ forecast.windScaleDay }}级 : {{ forecast.humidity }}% : {{ forecast.precip }}mm : {{ forecast.uvIndex }} : {{ forecast.sunrise }} : {{ forecast.sunset }}
        </li>
      </ul>
    </div>
  </template>
  
  <script>
  import { ref } from 'vue';
  
  export default {
    setup() {
      const cityId = ref('');
      const forecastData = ref([]);
  
      async function searchWeatherForecast() {
        const apiKey = 'fb24c8d1936c4a24bb097b522d49c274';
        if (cityId.value.trim()) {
          const url = `https://devapi.qweather.com/v7/weather/3d?key=${apiKey}&location=${cityId.value}`;
  
          try {
            const response = await fetch(url);
            const data = await response.json();
  
            if (response.ok) {
              forecastData.value = data.daily;
            } else {
              console.error('Error fetching weather data:', data);
            }
          } catch (error) {
            console.error('Error during fetch:', error);
          }
        } else {
          alert('请输入有效的城市ID');
        }
      }
  
      return {
        cityId,
        forecastData,
        searchWeatherForecast
      };
    }
  };
  </script>